package com.keon.jianbao.base;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.keon.jianbao.AppConfig;
import com.keon.jianbao.R;
import com.keon.jianbao.api.SimpleHandler;
import com.keon.jianbao.bean.Entity;
import com.keon.jianbao.bean.ListEntity;
import com.keon.jianbao.bean.Result;
import com.keon.jianbao.ui.widget.BottomScrollView;
import com.keon.jianbao.ui.widget.EmptyLayout;
import com.keon.jianbao.ui.widget.NoScrollGridView;
import com.keon.jianbao.util.StringUtils;
import com.keon.jianbao.util.TDevice;

import org.apache.http.Header;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * Created by keon on 2015/9/24.
 */
public abstract class BaseGirdViewFragment<T extends Entity> extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, AdapterView.OnItemClickListener, BottomScrollView.OnScrollToBottomListener {
    public static final String BUNDLE_KEY_CATALOG = "BUNDLE_KEY_CATALOG";

    public static final int STATE_NONE = 0;
    public static final int STATE_REFRESH = 1;
    public static final int STATE_LOADMORE = 2;
    public static final int STATE_NOMORE = 3;
    public static final int STATE_PRESSNONE = 4;// 正在下拉但还没有到刷新的状态
    public static int mState = STATE_NONE;

    protected int _loadmoreText;
    protected int _loadFinishText;
    protected int _noDateText;

    @Bind(R.id.swiperefreshlayout)
    protected SwipeRefreshLayout mSwipeRefreshLayout;
    @Bind(R.id.gridview)
    protected NoScrollGridView mGridview;
    @Bind(R.id.error_layout)
    protected EmptyLayout mErrorLayout;
    @Bind(R.id.gridViewScroll)
    protected BottomScrollView mGridViewScroll;
    @Bind(R.id.progressbar)
    ProgressBar progress;
    @Bind(R.id.text)
    TextView text;
    @Bind(R.id.footer)
    LinearLayout mFooterView;

    protected BaseGridViewAdapter<T> mAdapter;

    protected int mStoreEmptyState = -1;

    protected int mCurrentPage = 1;

    protected int mCatalog = 1;

    private ParserTask mParserTask;

    private int lastY = 0;

    protected SimpleHandler mHandler = new SimpleHandler() {

        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              byte[] responseBytes) {

            super.onSuccess(statusCode, headers, responseBytes);
            if (isAdded()) {
                if (mState == STATE_REFRESH) {
                    onRefreshNetworkSuccess();
                }

                try {
                    Result result = new Result(responseBytes);
                    if (result.getStatus() == 1) {
                        executeParserTask(result.getContent());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_pull_refresh_gridview;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if (args != null) {
            mCatalog = args.getInt(BUNDLE_KEY_CATALOG, 0);
        }

        _loadmoreText = R.string.loading;
        _loadFinishText = R.string.loading_no_more;
        _noDateText = R.string.error_view_no_data;
    }

    @Override
    public void initView(View view) {
        mHandler.setContext((BaseActivity) getActivity());
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeResources(
                R.color.swiperefresh_color1, R.color.swiperefresh_color2,
                R.color.swiperefresh_color3, R.color.swiperefresh_color4);

        mErrorLayout.setOnLayoutClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mCurrentPage = 1;
                mState = STATE_REFRESH;
                mErrorLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                requestData(true);
            }
        });

        mGridview.setOnItemClickListener(this);
        mGridViewScroll.setOnScrollToBottomLintener(this);

        if (mAdapter != null) {
            mGridview.setAdapter(mAdapter);
            mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        } else {
            mAdapter = getListAdapter();
            mGridview.setAdapter(mAdapter);

            if (requestDataIfViewCreated()) {
                mErrorLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                mState = STATE_NONE;
                requestData(false);
            } else {
                mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
            }

        }
        if (mStoreEmptyState != -1) {
            mErrorLayout.setErrorType(mStoreEmptyState);
        }
    }

    @Override
    public void onRefresh() {
        if (mState == STATE_REFRESH) {
            return;
        }
        // 设置顶部正在刷新
        setSwipeRefreshLoadingState();
        mCurrentPage = 1;
        mState = STATE_REFRESH;
        requestData(true);
    }

    private void setSwipeRefreshLoadingState() {
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.setRefreshing(true);
            // 防止多次重复刷新
            mSwipeRefreshLayout.setEnabled(false);
        }
    }

    protected void requestData(boolean refresh) {
        sendRequestData();
    }

    protected void sendRequestData() {
    }

    protected abstract BaseGridViewAdapter<T> getListAdapter();

    protected boolean requestDataIfViewCreated() {
        return true;
    }

    protected void onRefreshNetworkSuccess() {
    }

    private void executeParserTask(String data) {
        cancelParserTask();
        mParserTask = new ParserTask(data);
        mParserTask.execute();
    }

    private void cancelParserTask() {
        if (mParserTask != null) {
            mParserTask.cancel(true);
            mParserTask = null;
        }
    }

    @Override
    public void onScrollBottomListener(boolean isBottom) {
        if (mAdapter == null || mAdapter.getCount() == 0) {
            return;
        }
        // 数据已经全部加载，或数据为空时，或正在加载，不处理滚动事件
        if (mState == STATE_LOADMORE || mState == STATE_REFRESH) {
            return;
        }
        // 判断是否滚动到底部
        boolean scrollEnd = false;

        if (isBottom == true) {
            scrollEnd = true;
        }

        if (mState == STATE_NONE && scrollEnd) {
            if (mAdapter.getState() == BaseListAdapter.STATE_LOAD_MORE
                    || mAdapter.getState() == BaseListAdapter.STATE_NETWORK_ERROR) {
                mCurrentPage++;
                mState = STATE_LOADMORE;
                requestData(false);
                setFooterViewLoading();
            }
        }
    }

    class ParserTask extends AsyncTask<Void, Void, String> {

        private final String reponseData;
        private boolean parserError;
        private List<T> list;

        public ParserTask(String data) {
            this.reponseData = data;
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                ListEntity<T> data = parseList(reponseData);
                if (list == null && data != null) {
                    list = data.getList();
                }
            } catch (Exception e) {
                e.printStackTrace();

                parserError = true;
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (parserError) {
                executeOnLoadDataError(null);
            } else {
                executeOnLoadDataSuccess(list);
                executeOnLoadFinish();
            }
        }

    }

    protected ListEntity<T> parseList(String reponseData) {
        return null;
    }

    protected void executeOnLoadDataSuccess(List<T> data) {
        if (data == null) {
            data = new ArrayList<T>();
        }

/*        if (mResult != null && !mResult.OK()) {
//            AppContext.showToast(mResult.getErrorMessage());
            ((BaseActivity) getActivity()).showToast(mResult.getMsg());
            // 注销登陆，密码已经修改，cookie，失效了
            AppContext.getInstance().Logout();
        }*/

        mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        if (mCurrentPage == 1) {
            mAdapter.clear();
        }

        for (int i = 0; i < data.size(); i++) {
            if (compareTo(mAdapter.getData(), data.get(i))) {
                data.remove(i);
                i--;
            }
        }
        int adapterState = BaseListAdapter.STATE_EMPTY_ITEM;
        mFooterView.setBackgroundDrawable(null);
        if ((mAdapter.getCount() + data.size()) == 0) {
            adapterState = BaseListAdapter.STATE_EMPTY_ITEM;

            progress.setVisibility(View.GONE);
            mFooterView.setVisibility(View.VISIBLE);
            text.setText(_noDateText);

        } else if (data.size() == 0
                || (data.size() < getPageSize() && mCurrentPage > 0)) {
            adapterState = BaseListAdapter.STATE_NO_MORE;
            mAdapter.notifyDataSetChanged();

            mFooterView.setVisibility(View.VISIBLE);
            progress.setVisibility(View.GONE);
            text.setVisibility(View.VISIBLE);
            text.setText(_loadFinishText);
        } else {
            adapterState = BaseListAdapter.STATE_LOAD_MORE;

            setFooterViewLoading();
        }
        mAdapter.setState(adapterState);
        mAdapter.addData(data);
        // 判断等于是因为最后有一项是listview的状态
 /*       if (mAdapter.getCount() == 1) {

            if (needShowEmptyNoData()) {
                mErrorLayout.setErrorType(EmptyLayout.NODATA);
            } else {
                mAdapter.setState(BaseListAdapter.STATE_EMPTY_ITEM);
                mAdapter.notifyDataSetChanged();
            }
        }*/
    }

    protected boolean compareTo(List<? extends Entity> data, Entity enity) {
        int s = data.size();
        if (enity != null) {
            for (int i = 0; i < s; i++) {
                if (enity.getId() == data.get(i).getId()) {
                    return true;
                }
            }
        }
        return false;
    }

    protected int getPageSize() {
        return AppConfig.PAGE_SIZE;
    }

    protected boolean needShowEmptyNoData() {
        return true;
    }

    // 完成刷新
    protected void executeOnLoadFinish() {
        setSwipeRefreshLoadedState();
        mState = STATE_NONE;
    }


    protected void executeOnLoadDataError(String error) {
        if (mCurrentPage == 1) {
            mErrorLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
        } else {
            mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
            mAdapter.setState(BaseGridViewAdapter.STATE_NETWORK_ERROR);
            mAdapter.notifyDataSetChanged();

            mFooterView.setVisibility(View.VISIBLE);
            progress.setVisibility(View.GONE);
            text.setVisibility(View.VISIBLE);
            if (TDevice.hasInternet()) {
                text.setText("加载出错了");
            } else {
                text.setText("没有可用的网络");
            }
        }
    }

    private void setSwipeRefreshLoadedState() {
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.setRefreshing(false);
            mSwipeRefreshLayout.setEnabled(true);
        }
    }

    public void setFooterViewLoading(String loadMsg) {
        mFooterView.setVisibility(View.VISIBLE);
        progress.setVisibility(View.VISIBLE);
        text.setVisibility(View.VISIBLE);
        if (StringUtils.isEmpty(loadMsg)) {
            text.setText(_loadmoreText);
        } else {
            text.setText(loadMsg);
        }
    }

    public void setFooterViewLoading() {
        setFooterViewLoading("");
    }
}
